package br.ufrj.dcc.tp.server;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import br.ufrj.dcc.tp.common.Client;
import br.ufrj.dcc.tp.common.Message;

public class ServerService {
	
	private static Map<Client,Socket> clients;
	
	/**
	 * Retorna todos os sockets conectados ao servidor. É estático para manter a integridade
	 * entre as threads.
	 * */
	public static Map<Client,Socket> getClientsInstance() {
		if (clients == null) clients = new HashMap<Client,Socket>();
		return clients;
	}
	
	/**
	 * Envia a mensagem para todos os clientes conectados
	 * */
	public static void sendObjectForAllSockets(Object object) {
	
		for (Client client : clients.keySet()) {
			try {
				// caso algum cliente se desconectou, remove da lista
				if(clients.get(client).isClosed()) {
					clients.remove(client);
				} else {
					ObjectOutputStream  out = new ObjectOutputStream(clients.get(client).getOutputStream());
					System.out.println("[ServerService] " + object);
					out.writeObject(object);
					out.flush();
				}
			} catch (IOException e) {
				System.out.println("[ServerService] Failed to send message object to all sockets");
				e.printStackTrace();
			}
		}
		
	}
	
	public static void sendMessageForAllSockets(Message object) {
		
		for (Client client : clients.keySet()) {
			try {
				// caso algum cliente se desconectou, remove da lista
				if(clients.get(client).isClosed()) {
					clients.remove(client);
				} else {
					ObjectOutputStream  out = new ObjectOutputStream(clients.get(client).getOutputStream());
					System.out.println("[ServerService] " + object);
					out.writeObject(object);
					out.flush();
				}
			} catch (IOException e) {
				System.out.println("[ServerService] Failed to send message object to all sockets");
				e.printStackTrace();
			}
		}
		
	}
	
}
